package com.century.sjt.activity.login;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.EMChat.widget.EaseSidebar;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.adapter.ChooseCountryAdapter;
import com.century.sjt.entity.Country;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.utils.PreferenceManager;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by 炳基 on 2016/8/5.
 * 国家/地区/语言
 * 选择列表
 */
public class ChooseCountryActivity extends BaseActivity {

    private SjtTitleBar titleBar;
    private ListView mList;
    private Boolean isDataChangeOk=true;
    private List<Country> mDatalist;
    private ChooseCountryAdapter adapter;
    protected EaseSidebar sidebar;
    private String mType = "0";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choosecountry);
        if (getIntent().getStringExtra("type")!=null){
            mType = getIntent().getStringExtra("type");
        }


        initView();
        initEvent();
    }
    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.tab_choose_country));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
//        titleBar.setRightIconResourc(getResources().getString(R.string.btn_yes));
        mList = (ListView) findViewById(R.id.list);
        sidebar = (EaseSidebar) findViewById(R.id.sidebar);

    }

    @Override
    protected void initEvent() {
        mDatalist = new ArrayList<>();
        adapter = new ChooseCountryAdapter(ChooseCountryActivity.this,0,mDatalist);
        mList.setAdapter(adapter);
        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                PreferenceManager.getInstance().setMobileCode(mDatalist.get(i).getMobileCode());
                PreferenceManager.getInstance().setCountryCode(mDatalist.get(i).getCountryCode());
                PreferenceManager.getInstance().setCountryName(mDatalist.get(i).getCountryName());
                Intent intent = new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("countryName", mDatalist.get(i).getCountryName());
                bundle.putString("mobileCode", mDatalist.get(i).getMobileCode());
                intent.putExtras(bundle);
                ChooseCountryActivity.this.setResult(RESULT_OK, intent);
                switch (mType){
                    case "register":
                        startActivity(new Intent(ChooseCountryActivity.this, RegisterActivity.class));
//                        finish();
                        break;
                    case "login":
//                        finish();
                        startActivity(new Intent(ChooseCountryActivity.this, LoginActivity.class));
                        break;
                    case "forgetowd":
                        finish();
                        break;
                    default:
                        Intent intent1 = new Intent();
                        intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent1.setClass(ChooseCountryActivity.this, LoginActivity.class);
                        startActivity(intent1);
                        break;
                }

            }
        });
        sidebar.setListView(mList);
//
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        getCountry();
    }

    @Override
    protected void onStart() {
        super.onStart();
        String language = PreferenceManager.getInstance().getCurrentLanguage();
        if ("".equals(language)||null==language){

        }
    }

    private void getLanguage(){
        mDatalist.clear();
        TypedArray translatecode = getResources().obtainTypedArray(R.array.translatecode);
        TypedArray translateName = getResources().obtainTypedArray(R.array.translateName);
        for(int i = 0;i<translatecode.length();i++){
            Country country = new Country();
            country.setCountryName(translateName.getString(i));
            country.setCountryCode(translatecode.getString(i));
            mDatalist.add(country);
        }
    }

    private void getCountry(){
        Locale locale = getResources().getConfiguration().locale;
        final String language = locale.getLanguage();
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddressManageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.getCountryList, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                            mDatalist.clear();
                            JSONArray countryList = res.getJSONArray("data");
                            for (int i = 0; i < countryList.length(); i++) {
                                JSONObject aData = (JSONObject) countryList.get(i);
                                Country country = new Country();
                                country.setCountryCode(aData.getString("countryCode"));
                                country.setCountryName(aData.getString("countryName"));
                                country.setMobileCode(aData.getString("mobileCode"));
                                country.setInitialLetter(aData.getString("initialLetter"));
                                country.setNationalFlag(aData.getString("nationalFlag"));
                                mDatalist.add(country);
                            }
                    } else {//失败
                        TipUtil.showToast(message, ChooseCountryActivity.this, 1);
                    }
                    getMContactList(mDatalist);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), ChooseCountryActivity.this, 1);
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), ChooseCountryActivity.this, 1);
                TipUtil.closeProgressDialog();
                adapter.notifyDataSetChanged();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
                map.put("code", language);
//                map.put("paging.currentPage",String.valueOf(iCurrPage));//当前页码
//                map.put("paging.pageSize",Constant.PAGESIZE+" ");//查询条数

                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }




    /**
     * 排序
     */
    protected void getMContactList(List<Country> mDatalist) {
        synchronized (mDatalist) {
            //获取列表
            if(mDatalist == null){
                return;
            }
            // 排序
            Collections.sort(mDatalist, new Comparator<Country>() {

                @Override
                public int compare(Country lhs, Country rhs) {
                    if(lhs.getInitialLetter().equals(rhs.getInitialLetter())){

                        return lhs.getCountryName().compareTo(rhs.getCountryName());
                    }else{
                        if("#".equals(lhs.getInitialLetter())){
                            return 1;
                        }else if("#".equals(rhs.getInitialLetter())){
                            return -1;
                        }
                        return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
                    }

                }
            });
        }
    }
}
